package com.example.translateappjava.Utils;

import java.time.Duration;
import java.time.Instant; // 更适合处理带'Z'的UTC时间戳
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Locale;

public class DateUtilsJavaTime {

    // 解析服务器返回的日期时间格式 (如: "2025-06-03T10:31:28Z")
    // DateTimeFormatter.ISO_INSTANT 可以直接解析这种带 'Z' 的UTC时间戳
    // 或者也可以用 DateTimeFormatter.ISO_OFFSET_DATE_TIME
    // private static final DateTimeFormatter SERVER_DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT;
    // 注意: ISO_INSTANT 解析出来的是 Instant 对象。如果想用 ZonedDateTime 解析，可以这样：
    private static final DateTimeFormatter SERVER_ZONED_DATE_TIME_FORMATTER = DateTimeFormatter.ISO_ZONED_DATE_TIME;


    // 目标格式：YYYY-MM-DD 星期X
    private static final DateTimeFormatter ABSOLUTE_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd EEEE", Locale.CHINA);

    // 阈值：多少天以内显示相对时间
    private static final int RELATIVE_TIME_THRESHOLD_DAYS = 3;

    public static String formatPostTimeSmart(String serverUtcTimeString) {
        if (serverUtcTimeString == null || serverUtcTimeString.isEmpty()) {
            return "未知时间";
        }

        ZonedDateTime postDateTimeInSystemZone;
        try {
            // 方法1: 使用 ISO_ZONED_DATE_TIME 解析为 ZonedDateTime
            ZonedDateTime utcZonedDateTime = ZonedDateTime.parse(serverUtcTimeString, SERVER_ZONED_DATE_TIME_FORMATTER);
            // 将UTC时间转换为当前系统默认时区的时间
            postDateTimeInSystemZone = utcZonedDateTime.withZoneSameInstant(ZoneId.systemDefault());

            // 方法2: 使用 ISO_INSTANT 解析为 Instant，然后转换为 ZonedDateTime (效果类似)
            // Instant instant = Instant.parse(serverUtcTimeString); // Instant 本身就是UTC的
            // postDateTimeInSystemZone = instant.atZone(ZoneId.systemDefault());

        } catch (DateTimeParseException e) {
            System.err.println("Error parsing UTC date-time string: " + serverUtcTimeString);
            e.printStackTrace();
            return "无法格式化日期";
        }

        // 获取当前系统默认时区的当前时间
        ZonedDateTime nowInSystemZone = ZonedDateTime.now(ZoneId.systemDefault());

        // 计算时间差
        Duration duration = Duration.between(postDateTimeInSystemZone, nowInSystemZone);

        // 将 ZonedDateTime 转换为 LocalDateTime 以便获取天数等，或者直接在ZonedDateTime上操作
        // 注意：toDays() on Duration is based on 24-hour periods, not calendar days.
        // For more precise "X days ago" based on calendar day changes, a different approach might be needed
        // but for most "X days ago" scenarios, Duration.toDays() is acceptable.
        long daysDifference = duration.toDays();

        if (postDateTimeInSystemZone.isAfter(nowInSystemZone)) { // 帖子时间在未来
            return postDateTimeInSystemZone.format(ABSOLUTE_DATE_FORMATTER);
        }

        if (daysDifference < RELATIVE_TIME_THRESHOLD_DAYS) {
            if (daysDifference == 0) { // 今天
                long hoursDifference = duration.toHours();
                if (hoursDifference == 0) {
                    long minutesDifference = duration.toMinutes();
                    if (minutesDifference == 0) {
                        long secondsDifference = duration.getSeconds();
                        if (secondsDifference < 10 && secondsDifference >=0) return "刚刚";
                        return Math.max(1, secondsDifference) + "秒前";
                    }
                    return minutesDifference + "分钟前";
                }
                return hoursDifference + "小时前";
            } else if (daysDifference == 1) {
                // "昨天 HH:mm"
                return "昨天 " + postDateTimeInSystemZone.format(DateTimeFormatter.ofPattern("HH:mm", Locale.CHINA));
            } else { // 2天前 (因为阈值是3天)
                return daysDifference + "天前";
            }
        } else {
            // 大于等于阈值天数，显示绝对日期和星期
            return postDateTimeInSystemZone.format(ABSOLUTE_DATE_FORMATTER);
        }
    }

    public static void main(String[] args) {
        // 当前时间 (UTC)
        Instant nowInstant = Instant.now();

        // 模拟服务器返回的时间 (UTC)
        String timeJustNowUtc = nowInstant.minusSeconds(5).toString(); // Instant.toString() 就是 ISO 8601 UTC 格式
        String time5MinutesAgoUtc = nowInstant.minusSeconds(5 * 60).toString();
        String time2HoursAgoUtc = nowInstant.minusSeconds(2 * 60 * 60).toString();
        String timeYesterdayUtc = nowInstant.minusSeconds(24 * 60 * 60).atZone(ZoneId.systemDefault()).withHour(15).withMinute(30).toInstant().toString(); // 构造一个昨天的特定时间点(UTC)
        String time2DaysAgoUtc = nowInstant.minusSeconds(2 * 24 * 60 * 60).toString();
        String time3DaysAgoUtc = nowInstant.minusSeconds(3 * 24 * 60 * 60).toString();
        String time5DaysAgoUtc = nowInstant.minusSeconds(5 * 24 * 60 * 60).toString();
        String timeFutureUtc = nowInstant.plusSeconds(24 * 60 * 60).toString();


        System.out.println("当前设备时区: " + ZoneId.systemDefault());
        System.out.println("--- 测试相对时间 ---");
        System.out.println(timeJustNowUtc + " (UTC) -> " + formatPostTimeSmart(timeJustNowUtc));
        System.out.println(time5MinutesAgoUtc + " (UTC) -> " + formatPostTimeSmart(time5MinutesAgoUtc));
        System.out.println(time2HoursAgoUtc + " (UTC) -> " + formatPostTimeSmart(time2HoursAgoUtc));
        System.out.println(timeYesterdayUtc + " (UTC) -> " + formatPostTimeSmart(timeYesterdayUtc));
        System.out.println(time2DaysAgoUtc + " (UTC) -> " + formatPostTimeSmart(time2DaysAgoUtc));
        System.out.println("--- 测试绝对时间 (应切换格式) ---");
        System.out.println(time3DaysAgoUtc + " (UTC) -> " + formatPostTimeSmart(time3DaysAgoUtc));
        System.out.println(time5DaysAgoUtc + " (UTC) -> " + formatPostTimeSmart(time5DaysAgoUtc));
        System.out.println("--- 测试未来时间 ---");
        System.out.println(timeFutureUtc + " (UTC) -> " + formatPostTimeSmart(timeFutureUtc));
        System.out.println("--- 测试你的实际数据 ---");
        String actualServerTime = "2025-06-03T10:31:28Z"; // 这是一个固定的过去UTC时间
        System.out.println(actualServerTime + " (UTC) -> " + formatPostTimeSmart(actualServerTime));
        String anotherActual = "2024-03-10T02:30:00Z"; // 假设今天是2024-03-13
        System.out.println(anotherActual + " (UTC) -> " + formatPostTimeSmart(anotherActual));
    }
}